package com.dms.modules.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dms.modules.product.entity.Product;
import com.dms.modules.product.entity.UserBehaviorStats;
import com.dms.modules.product.entity.UserBrowseHistory;
import com.dms.modules.product.entity.UserFavorite;
import com.dms.modules.product.mapper.ProductMapper;
import com.dms.modules.product.mapper.UserBehaviorStatsMapper;
import com.dms.modules.product.service.ProductService;
import com.dms.modules.product.service.RecommendationService;
import com.dms.modules.product.vo.ProductDetailVO;
import com.dms.modules.user.service.UserBrowseHistoryService;
import com.dms.modules.user.service.UserFavoriteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class RecommendationServiceImpl implements RecommendationService {

    @Autowired
    private ProductService productService;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private UserBehaviorStatsMapper behaviorStatsMapper;

    @Autowired
    private UserBrowseHistoryService browseHistoryService;

    @Autowired
    private UserFavoriteService favoriteService;

    @Override
    public List<ProductDetailVO> getPersonalizedRecommendations(Long userId, Integer limit) {
        // 1. 获取用户行为统计
        List<UserBehaviorStats> behaviorStats = behaviorStatsMapper.selectUserBehaviorStats(userId, 1, 10);
        
        // 2. 获取用户浏览历史
        List<UserBrowseHistory> browseHistory = browseHistoryService.getByUserId(userId, 10);
        
        // 3. 获取用户收藏
        List<UserFavorite> favorites = favoriteService.getByUserId(userId, 1, 10);
        
        // 4. 合并所有商品ID
        Set<Long> productIds = new HashSet<>();
        behaviorStats.forEach(stat -> productIds.add(stat.getCategoryId()));
        browseHistory.forEach(history -> productIds.add(history.getProductId()));
        favorites.forEach(favorite -> productIds.add(favorite.getTargetId()));
        
        // 5. 获取推荐商品
        List<Product> products = productMapper.selectRecommendedProducts(new ArrayList<>(productIds), limit);
        return convertToDetailVOList(products);
    }

    @Override
    public List<ProductDetailVO> getBrowseHistoryRecommendations(Long userId, Integer limit) {
        // 获取用户最近浏览的商品分类
        List<UserBrowseHistory> browseHistory = browseHistoryService.getByUserId(userId, 10);
        Set<Long> categoryIds = browseHistory.stream()
                .map(UserBrowseHistory::getCategoryId)
                .collect(Collectors.toSet());
        
        // 获取这些分类下的热门商品
        List<Product> products = productMapper.selectRecommendedProducts(new ArrayList<>(categoryIds), limit);
        return convertToDetailVOList(products);
    }

    @Override
    public List<ProductDetailVO> getFavoriteRecommendations(Long userId, Integer limit) {
        // 获取用户收藏的商品分类
        List<UserFavorite> favorites = favoriteService.getByUserId(userId, 1, 10);
        Set<Long> categoryIds = favorites.stream()
                .map(favorite -> favorite.getTargetId())
                .collect(Collectors.toSet());
        
        // 获取这些分类下的热门商品
        List<Product> products = productMapper.selectRecommendedProducts(new ArrayList<>(categoryIds), limit);
        return convertToDetailVOList(products);
    }

    @Override
    public List<ProductDetailVO> getSearchHistoryRecommendations(Long userId, Integer limit) {
        // 获取用户搜索历史中的关键词
        List<String> searchKeywords = productService.getSearchHistory(userId, 10);
        
        // 使用关键词搜索商品
        List<Product> products = new ArrayList<>();
        for (String keyword : searchKeywords) {
            ProductSearchDTO searchDTO = new ProductSearchDTO();
            searchDTO.setKeyword(keyword);
            searchDTO.setPageSize(limit);
            products.addAll(productService.search(searchDTO).getRecords());
        }
        
        // 去重并限制数量
        products = products.stream()
                .distinct()
                .limit(limit)
                .collect(Collectors.toList());
        
        return convertToDetailVOList(products);
    }

    private List<ProductDetailVO> convertToDetailVOList(List<Product> products) {
        if (products == null || products.isEmpty()) {
            return Collections.emptyList();
        }
        return products.stream()
                .map(product -> {
                    ProductDetailVO vo = new ProductDetailVO();
                    vo.setId(product.getId());
                    vo.setName(product.getName());
                    vo.setPrice(product.getPrice());
                    vo.setOriginalPrice(product.getOriginalPrice());
                    vo.setStock(product.getStock());
                    vo.setStatus(product.getStatus());
                    vo.setDescription(product.getDescription());
                    vo.setImages(Arrays.asList(product.getImages().split(",")));
                    vo.setSpecs(product.getSpecs());
                    vo.setSales(product.getSales());
                    vo.setViewCount(product.getViewCount());
                    return vo;
                })
                .collect(Collectors.toList());
    }
} 